from CoreUrlAnalyzeMethods import UrlAnalyzer
from PyQt5.QtCore import QThread, pyqtSignal
from DataBean import ImageBean

import urllib.request
import datetime,time
import re

class UrlGetThread(QThread):

    url_signal = pyqtSignal(ImageBean)
    
    def __init__(self, url):
        super(UrlGetThread, self).__init__()
        self.bcyurl = url

    def run(self):
        coreAnalyze = UrlAnalyzer()
        imglist = coreAnalyze.getImgList(self.bcyurl)
        print ("共解析出", len(imglist), "条图片链接！")
        for imgbean in imglist:
            self.url_signal.emit(imgbean)

class ImgDownloadThread(QThread):

    download_signal = pyqtSignal(str)
    now_time = datetime.datetime.now()
    default_album = now_time.strftime("%Y%m%d")

    def __init__(self, imglist, savepath):
        super(ImgDownloadThread, self).__init__()
        self.img_list = imglist
        self.save_path = savepath

    def run(self):
        coreAnalyze = UrlAnalyzer()
        for img in self.img_list:
            if img.getAlbum().strip()=='':
                img.setAlbum(self.default_album)
            sub_path = re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])","",img.getAlbum())
            path = self.save_path + '/' + sub_path + '/'
            coreAnalyze.downloadImg(img.getImgUrl(), img.getImgName(), path)
            self.download_signal.emit(img.getImgName() + '-completed-')
        self.download_signal.emit('-----All Tasks Completed!-----')


    